package com.esinhai.tz.service.impl;

import com.esinhai.tz.common.Const;
import com.esinhai.tz.common.ServerResponse;
import com.esinhai.tz.dao.OperLogMapper;
import com.esinhai.tz.dao.UserTzMapper;
import com.esinhai.tz.pojo.OperLog;
import com.esinhai.tz.pojo.UserTz;
import com.esinhai.tz.pojo.UserTzVo;
import com.esinhai.tz.pojo.UserTzWithBLOBs;
import com.esinhai.tz.service.IUserTzService;
import com.esinhai.tz.util.ToolUtil;
import com.esinhai.tz.webservice.WebServiceFrontImages;
import com.github.pagehelper.StringUtil;
import net.sf.json.JSONObject;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.fileupload.disk.DiskFileItem;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import sun.misc.BASE64Encoder;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by 32988 on 2018/4/12.
 */
@Service("userTzServiceImpl")
public class UserTzServiceImpl implements IUserTzService {

    private Logger logger = LoggerFactory.getLogger(WebServiceFrontImages.class);

    @Autowired
    private UserTzMapper userTzMapper;

    @Autowired
    private OperLogMapper operLogMapper;

    @Override
    public ServerResponse<UserTzWithBLOBs> saveUserInfo(MultipartFile[] imgFiles, MultipartFile[] faceFiles) {
        try {
            OperLog operLog = new OperLog();
            String faceDatas = ToolUtil.fileToStringUtile(faceFiles);
            UserTzWithBLOBs userTzWithBLOBs = new UserTzWithBLOBs();
            String imgDatas = "";
            String rawData = "";
            BASE64Encoder encoder = new BASE64Encoder();
            for (MultipartFile imgFile : imgFiles) {
                String filename = imgFile.getOriginalFilename();
                String prefix = filename.substring(filename.lastIndexOf(".") + 1);
                //ToolUtil.doFile(ToolUtil.reloadProperties(Const.FILE_PATH),imgFile,imgFile.getName());
                if ("bmp".equals(prefix)) {
                    rawData = rawData + "bmp:" + encoder.encode(imgFile.getBytes()) + Const.RAW_DATA;
                } else if ("txt".equals(prefix)) {
                    CommonsMultipartFile cf = (CommonsMultipartFile) imgFile;
                    DiskFileItem fi = (DiskFileItem) cf.getFileItem();
                    InputStream inputStream = fi.getInputStream();
                    String IDCardInfo = ToolUtil.readToString(inputStream);
                    String result = "";
                    if (!StringUtil.isEmpty(IDCardInfo)) {
                        int leng = IDCardInfo.indexOf("{");
                        result = IDCardInfo.substring(leng);
                        String[] a = result.split("}");
                        JSONObject json = JSONObject.fromObject(a[0] + "}");
                        imgDatas = imgDatas + "fingerpring_Byte" + a[1] + "}" + Const.FINGERPRING;

                        if (json != null) {
                            userTzWithBLOBs.setAddress(json.optString("address"));
                            userTzWithBLOBs.setName(json.optString("name"));
                            userTzWithBLOBs.setIdcard(json.optString("idNo"));
                            userTzWithBLOBs.setCsny(json.optString("brithday"));
                            userTzWithBLOBs.setSex(json.optString("sexy"));
                            userTzWithBLOBs.setPhoto(json.optString("photoPath"));
                            userTzWithBLOBs.setUserId(json.optString("userId"));
                            String sendString = json.opt("encodeStream") + "";
                            rawData = rawData + "encodeStream=:" + sendString + Const.RAW_DATA;
                        }
                    }
                } else {
                    String data = encoder.encode(imgFile.getBytes());
                    imgDatas = data + Const.FINGERPRING + imgDatas;
                }
            }
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            userTzWithBLOBs.setFingerpring(imgDatas);
            userTzWithBLOBs.setFace(faceDatas);
            userTzWithBLOBs.setRawData(rawData);
            if (userTzMapper.selectByIdcard(userTzWithBLOBs.getIdcard()) > 0) {

                UserTz user = new UserTz();
                user.setIdcard(userTzWithBLOBs.getIdcard());
                List<UserTzWithBLOBs> userTzWithBLOBsList = userTzMapper.selectByParams(user);
                String object_id = userTzWithBLOBsList.get(0).getObjectId();

                userTzWithBLOBs.setObjectId(object_id);
                userTzWithBLOBs.setBesyn("0");
                //更新操作
                operLog.setObjId(userTzWithBLOBs.getObjectId());
                operLog.setClsId(ToolUtil.reloadProperties("cls.id"));
                operLog.setUserId(ToolUtil.reloadProperties("user.id"));
                operLog.setOperLogId(UUID.randomUUID().toString().replaceAll("-", ""));
                operLog.setStatus("0");
                operLog.setOperType("2");
                SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
                operLog.setOperTime(formatter.format(new Date()));
                operLogMapper.insert(operLog);
                userTzMapper.updateByPrimaryKeyWithBLOBs(userTzWithBLOBs);
                //判断是否已经生成了文件
                File file = new File(ToolUtil.reloadProperties(Const.FILE_PATH) + user.getIdcard() + "\\");
                if (file != null) {
                    if (file.listFiles() != null) {
                        if (file.listFiles().length > 0) {
                            ToolUtil.deleteDir(file);
                        }
                    }
                }
            } else {
                userTzWithBLOBs.setObjectId(uuid);
                operLog.setObjId(userTzWithBLOBs.getObjectId());
                operLog.setClsId(ToolUtil.reloadProperties("cls.id"));
                operLog.setUserId(ToolUtil.reloadProperties("user.id"));
                operLog.setOperLogId(UUID.randomUUID().toString().replaceAll("-", ""));
                operLog.setStatus("0");
                operLog.setOperType("1");
                SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
                operLog.setOperTime(formatter.format(new Date()));
                operLogMapper.insert(operLog);
                userTzMapper.insert(userTzWithBLOBs);

            }
            //记录日志用


            return ServerResponse.createBySuccess("保存成功", userTzWithBLOBs);
        } catch (Exception e) {
            logger.error("保存失败：", e);
        }
        return null;
    }

    @Override
    public ServerResponse<String> saveWebServiceFrontImages(MultipartFile[] imgFiles, MultipartFile[] faceFiles) {
        BASE64Encoder encoder = new BASE64Encoder();
        try {
            String idcard = "";
            //为了获取idcard的信息
            for (MultipartFile imgFile : imgFiles) {
                String filename = imgFile.getOriginalFilename();
                String prefix = filename.substring(filename.lastIndexOf(".") + 1);
                if ("txt".equals(prefix)) {
                    CommonsMultipartFile cf = (CommonsMultipartFile) imgFile;
                    DiskFileItem fi = (DiskFileItem) cf.getFileItem();
                    InputStream inputStream = fi.getInputStream();
                    String IDCardInfo = ToolUtil.readToString(inputStream);
                    String result = "";
                    if (!StringUtil.isEmpty(IDCardInfo)) {
                        int leng = IDCardInfo.indexOf("{");
                        result = IDCardInfo.substring(leng);
                        String[] a = result.split("}");
                        JSONObject json = JSONObject.fromObject(a[0] + "}");
                        if (json != null) {
                            idcard = json.optString("idNo");
                        }
                    }
                }
            }
            if (StringUtils.isEmpty(idcard)) {
                return ServerResponse.createByErrorMessage("txt文件错误或者文件丢失");
            }
            String status = "";
            if (faceFiles != null && faceFiles.length > 0) {
                //循环获取file数组中得文件
                for (MultipartFile faceFile : faceFiles) {
                    String filename = faceFile.getOriginalFilename();
                    if (filename.contains("front")) {
                        //正脸front 发送webservice
                        status = WebServiceFrontImages.hskjWebService(idcard, encoder.encode(faceFile.getBytes()));
                    }
                }
            }
            if ("0".equals(status)) {
                return ServerResponse.createBySuccess("操作成功", status);
            } else {
                return ServerResponse.createBySuccess("操作失败", status);
            }
        } catch (IOException e) {
            logger.error("人脸注册失败：", e);
        }
        return null;
    }

    @Override
    public ServerResponse<String> saveUserFaceImage() {
        UserTz userTz = new UserTz();
        userTz.setBesyn("0");
        List<UserTzWithBLOBs> userTzList = (List<UserTzWithBLOBs>) userTzMapper.selectByParams(userTz);
        for (UserTzWithBLOBs user : userTzList) {
            String status = "";
            if ("0".equals(user.getBesyn())) {
                if (!StringUtil.isEmpty(user.getFace())) {
                    //通过，分割出图片的base64数据
                    String[] faces = user.getFace().split(Const.SIGN);
                    for (String face : faces) {
                        //把base64转成图片放在对应的路径下
                        face = face.substring("front:".length());
                        status = WebServiceFrontImages.hskjWebService(user.getIdcard(), face);
                    }
                }
            }
        }

        return null;
    }

    public static void main(String[] args) {
        UserTzServiceImpl u = new UserTzServiceImpl();
        u.saveUserFaceImage();
    }


    @Override
    public ServerResponse<List<Map<String, Object>>> queryUserInfo(UserTz userTz) {
        List<UserTzWithBLOBs> userTzList = (List<UserTzWithBLOBs>) userTzMapper.selectByParams(userTz);
        int i = 0;
        // String path = ToolUtil.reloadProperties(Const.FILE_PATH);
        List<Map<String, Object>> list = new ArrayList();
        //遍历
        for (UserTzWithBLOBs user : userTzList) {

            File file = new File(ToolUtil.reloadProperties(Const.FILE_PATH) + user.getIdcard() + "\\");
            if (!file.exists() && !file.isDirectory()) {
                file.mkdir();
            }
            File[] files = file.listFiles();
            if (files.length == 0) {
                String path = ToolUtil.reloadProperties(Const.FILE_PATH) + user.getIdcard() + "\\";
                String[] faces = user.getFace().split(Const.SIGN);
                String[] rawDatas = user.getRawData().split("\\&");
                String[] fingerprings = user.getFingerpring().split("\\$");
                for (String face : faces) {
                    ToolUtil.generateImage(face, path, new Date().getTime() + ".jpg");
                }
                for (String rawData : rawDatas) {
                    if (!rawData.contains("encodeStream")) {
                        rawData = rawData.substring(4);
                        ToolUtil.generateImage(rawData, path, new Date().getTime() + ".jpg");
                    }
                }
                for (String fingerpring : fingerprings) {
                    if (!fingerpring.contains("fingerpring_Byte")) {
                        ToolUtil.generateImage(fingerpring, path, new Date().getTime() + ".jpg");
                    }
                }
                file = new File(ToolUtil.reloadProperties(Const.FILE_PATH) + user.getIdcard() + "\\");
                files = file.listFiles();
            }
            Map<String, Object> resultMap = new HashedMap();
            for (File f : files) {
                if (f.isFile()) {
                    resultMap.put(f.getName(), ToolUtil.reloadProperties("host.ip") + ":" + ToolUtil.reloadProperties("host.port") + "/" + "upload" + "/" + user.getIdcard() + "/" + f.getName());
                }
            }
            list.add(resultMap);
        }

        return ServerResponse.createBySuccess("查询成功", list);
    }

    public synchronized Map<String, Object> queryUserFaceInfo(UserTz userTz) {
        //通过userTz查询出值
        List<UserTzWithBLOBs> userTzList = (List<UserTzWithBLOBs>) userTzMapper.selectByParams(userTz);
        int i = 0;
        // String path = ToolUtil.reloadProperties(Const.FILE_PATH);
        List<Map<String, Object>> list = new ArrayList();
        for (UserTzWithBLOBs user : userTzList) {
            //ToolUtil.reloadProperties 通过Key读取配置文件的Value值
            //查看这个文件目录是否有文件
            File file = new File(ToolUtil.reloadProperties(Const.FILE_PATH) + user.getIdcard() + "\\");
            if (!file.exists() && !file.isDirectory()) {
                file.mkdir();
            }
            File[] files = file.listFiles();
            //如果这个目录下没有文件就 解析数据库中的base64值转图片
            synchronized (files) {
                if (files.length == 0) {
                    //获取路径
                    String path = ToolUtil.reloadProperties(Const.FILE_PATH) + user.getIdcard() + "\\";
                    if (!StringUtil.isEmpty(user.getFace())) {
                        //通过，分割出图片的base64数据
                        String[] faces = user.getFace().split(Const.SIGN);
                        for (String face : faces) {
                            //把base64转成图片放在对应的路径下
                            String fileName = new Date().getTime() + "";
                            if (face.contains("front")) {
                                fileName = "front-" + user.getIdcard();
                                face = face.substring("front:".length());
                            }
                            ToolUtil.generateImage(face, path, fileName + ".jpg");
                        }
                    }
                    if (!StringUtil.isEmpty(user.getRawData())) {
                        String[] rawDatas = user.getRawData().split("\\&");
                        for (String rawData : rawDatas) {
                            if (!rawData.contains("encodeStream")) {
                                rawData = rawData.substring(4);
                                ToolUtil.generateImage(rawData, path, new Date().getTime() + ".jpg");
                            }
                        }
                    }
                    if (!StringUtil.isEmpty(user.getFingerpring())) {
                        String[] fingerprings = user.getFingerpring().split("\\$");
                        for (String fingerpring : fingerprings) {
                            if (!fingerpring.contains("fingerpring_Byte")) {
                                ToolUtil.generateImage(fingerpring, path, new Date().getTime() + ".jpg");
                            }
                        }
                    }
                    file = new File(ToolUtil.reloadProperties(Const.FILE_PATH) + user.getIdcard() + "\\");
                    files = file.listFiles();
                }
            }
            Map<String, Object> resultMap = new HashedMap();

            //遍历文件
            String url = "";
            for (File f : files) {
                if (f.isFile() && f.getName().contains("front")) {
                    resultMap.put(f.getName(), ToolUtil.reloadProperties("host.ip") + ":" + ToolUtil.reloadProperties("host.port") + "/" + "upload" + "/" + user.getIdcard() + "/" + f.getName());
                    //在tomcat中配置的虚拟路径，获得对应的图片地址
                    //front_url = front_url + Const.RAW_DATA + "/" + "upload" + "/" + user.getIdcard() + "/" + f.getName();
                    url = url + Const.RAW_DATA + "/" + "upload" + "/" + user.getIdcard() + "/" + f.getName();
                } else if (f.isFile()) {
                    url = url + Const.RAW_DATA + "/" + "upload" + "/" + user.getIdcard() + "/" + f.getName();
                }
            }
            user.setPhoto(url);
            list.add(resultMap);
            url = "";
        }
        Map<String, Object> mmp = new HashMap<String, Object>();


        String isIdCard = "no";
        String isFaceImage = "no";
        String isFingerprint = "no";
        String isRawData = "no";
        if (!CollectionUtils.isEmpty(userTzList)) {
            if (!StringUtils.isEmpty(userTzList.get(0).getIdcard())) {
                isIdCard = "yes";
            }
            if (!StringUtils.isEmpty(userTzList.get(0).getFingerpring())) {
                isFingerprint = "yes";
            }
            if (!StringUtils.isEmpty(userTzList.get(0).getFace())) {
                isFaceImage = "yes";
            }
            if (!StringUtils.isEmpty(userTzList.get(0).getRawData())) {
                isRawData = "yes";
            }
        }
        mmp.put("isIdCard", isIdCard);
        mmp.put("isFaceImage", isFaceImage);
        mmp.put("isFingerprint", isFingerprint);
        mmp.put("isRawData", isRawData);

        for (UserTzWithBLOBs user : userTzList) {
            user.setFingerpring("");
            user.setRawData("");
            user.setFace("");
        }
        mmp.put("rows", userTzList);
        mmp.put("total", userTzList.size());
        mmp.put("imageUrl", list);

        return mmp;
    }


    public Map<String, Object> queryUserFaceInfo(String idcard) {
        //通过userTz查询出值
        UserTz userTz = new UserTz();
        userTz.setIdcard(idcard);
        List<UserTzWithBLOBs> userTzList = (List<UserTzWithBLOBs>) userTzMapper.selectByParams(userTz);
        int i = 0;
        // String path = ToolUtil.reloadProperties(Const.FILE_PATH);
        List<Map<String, Object>> list = new ArrayList();
        for (UserTzWithBLOBs user : userTzList) {
            //ToolUtil.reloadProperties 通过Key读取配置文件的Value值
            //查看这个文件目录是否有文件

            File file = new File(ToolUtil.reloadProperties(Const.FILE_PATH) + user.getIdcard() + "\\");
            if (!file.exists() && !file.isDirectory()) {
                file.mkdirs();
            }
            File[] files = file.listFiles();
            //如果这个目录下没有文件就 解析数据库中的base64值转图片
            synchronized (files) {
                if (files.length == 0) {
                    //获取路径
                    String path = ToolUtil.reloadProperties(Const.FILE_PATH) + user.getIdcard() + "\\";
                    if (!StringUtil.isEmpty(user.getFace())) {
                        //通过，分割出图片的base64数据
                        String[] faces = user.getFace().split(Const.SIGN);
                        for (String face : faces) {
                            //把base64转成图片放在对应的路径下
                            String fileName = new Date().getTime() + "";
                            if (face.contains("front")) {
                                fileName = "front-" + user.getIdcard();
                                face = face.substring("front:".length());
                            }
                            ToolUtil.generateImage(face, path, fileName + ".jpg");
                        }
                    }
                    if (!StringUtil.isEmpty(user.getRawData())) {
                        String[] rawDatas = user.getRawData().split("\\&");
                        for (String rawData : rawDatas) {
                            if (!rawData.contains("encodeStream")) {
                                rawData = rawData.substring(4);
                                ToolUtil.generateImage(rawData, path, new Date().getTime() + ".jpg");
                            }
                        }
                    }
                    if (!StringUtil.isEmpty(user.getFingerpring())) {
                        String[] fingerprings = user.getFingerpring().split("\\$");
                        for (String fingerpring : fingerprings) {
                            if (!fingerpring.contains("fingerpring_Byte")) {
                                ToolUtil.generateImage(fingerpring, path, new Date().getTime() + ".jpg");
                            }
                        }
                    }
                    file = new File(ToolUtil.reloadProperties(Const.FILE_PATH) + user.getIdcard() + "\\");
                    files = file.listFiles();
                }
            }
            Map<String, Object> resultMap = new HashedMap();
            String url = "";
            //遍历文件
            for (File f : files) {
                if (f.isFile() && f.getName().contains("front")) {
                    resultMap.put(f.getName(), ToolUtil.reloadProperties("host.ip") + ":" + ToolUtil.reloadProperties("host.port") + "/" + "upload" + "/" + user.getIdcard() + "/" + f.getName());
                    //在tomcat中配置的虚拟路径，获得对应的图片地址
                    //front_url = front_url + Const.RAW_DATA + "/" + "upload" + "/" + user.getIdcard() + "/" + f.getName();
                    url = url + Const.RAW_DATA + "/" + "upload" + "/" + user.getIdcard() + "/" + f.getName();
                } else if (f.isFile()) {
                    url = url + Const.RAW_DATA + "/" + "upload" + "/" + user.getIdcard() + "/" + f.getName();
                }
            }
            user.setPhoto(url);
            list.add(resultMap);
        }
        Map<String, Object> mmp = new HashMap<String, Object>();


        String isIdCard = "no";
        String isFaceImage = "no";
        String isFingerprint = "no";
        String isRawData = "no";
        if (!CollectionUtils.isEmpty(userTzList)) {
            if (!StringUtils.isEmpty(userTzList.get(0).getIdcard())) {
                isIdCard = "yes";
            }
            if (!StringUtils.isEmpty(userTzList.get(0).getFingerpring())) {
                isFingerprint = "yes";
            }
            if (!StringUtils.isEmpty(userTzList.get(0).getFace())) {
                isFaceImage = "yes";
            }
            if (!StringUtils.isEmpty(userTzList.get(0).getRawData())) {
                isRawData = "yes";
            }
        }

        mmp.put("isIdCard", isIdCard);
        mmp.put("isFaceImage", isFaceImage);
        mmp.put("isFingerprint", isFingerprint);
        mmp.put("isRawData", isRawData);

        for (UserTzWithBLOBs user : userTzList) {
            user.setFingerpring("");
            user.setRawData("");
            user.setFace("");
        }
        mmp.put("rows", userTzList);
        mmp.put("total", userTzList.size());
        mmp.put("imageUrl", list);

        return mmp;
    }


    @Override
    public ServerResponse<String> deleteUserInfo(String objectId) {
        userTzMapper.deleteByPrimaryKey(objectId);
        return ServerResponse.createBySuccessMessage("删除成功");
    }

}
